import React, { useEffect, useState } from 'react';
import { useNavigate, useLocation } from "react-router-dom";
import styled from 'styled-components';
import { type } from "@tauri-apps/plugin-os";
import { WindowTitlebar } from "tauri-controls";
import { CheckCircleFilled } from '@ant-design/icons';

import { setToken, uuidTrim, get } from '../../utils';
import { tmpUuidGet } from 'services';

export const WxxQRCodeLoginPage = () => {

    const [qrcode, setQRCode] = useState<any>(null);

    const [count, setCount] = useState<number>(-1);

    const [status, setStatus] = useState<number>(1);

    const [uid, setUid] = useState<string>('');

    const navigate = useNavigate();

    const refreshQRCode = () => {
        //生成UUIs
        let uid = uuidTrim();
        console.log(uid);
        let page = 'pages/alogin/index';
        let envVersion = 'release';
        // /api/auth/get_wx_qrcode?page=pages%2Fconversation%2Findex&scene=sssssss
        // 请求
        get({
            url: `https://www.idns.link/api/auth/get_wx_qrcode?page=${encodeURIComponent(page)}&scene=${uid}&env_version=${envVersion}`,
        }).then((response) => {
            if (response.status === 200) {
                response.blob().then((array: Blob) => {
                    console.log(array);
                    var urlCreator = window.URL || window.webkitURL;
                    var imageUrl = urlCreator.createObjectURL(array);
                    setQRCode(imageUrl);
                });
            } else {
                //TODO
            }
        }).catch((err) => {
            console.log(err);
        });
        //启动后台轮询
        setUid(uid);
        setCount(1);
    };

    const refreshStatus = (uid: string) => {
        //通过UID获取到状态
        console.log(uid);
        try {
            tmpUuidGet(uid).then((res) => {
                console.log(res);
                //[uuid,category,extends,status]
                if (res && res.length == 4) {
                    // 1, 2:已经扫码， 3已经授权， 4：取消授权
                    if (res[3] === 3 || res[3] === 4) {
                        //完成
                        if (res[3] === 3) {
                            //保存Token
                            setToken(res[2]);
                            navigate('/login');
                        } else {
                            refreshQRCode();
                        }
                    } else {
                        //新建
                        setCount(count + 1)
                    }
                    setStatus(res[3]);
                }
            });
        } catch (err) {
            console.log(err);
        }
    };

    useEffect(() => {
        if (count >= 0 && uid && uid != '') {
            //
            setTimeout(() => {
                refreshStatus(uid);
            }, 1000);
        }
    }, [count, uid]);

    useEffect(() => {
        //请求后端获取二维码
        refreshQRCode();
    }, []);

    if (status === 2) {
        //已经扫描
        return (
            <Container data-tauri-drag-region style={{
                justifyContent: 'center'
            }}>
                <WindowControlsContainer data-tauri-drag-region
                    style={type() === 'macos' ? {
                        justifyContent: 'flex-start'
                    } : {
                        justifyContent: 'flex-end'
                    }}>
                    <WindowTitlebar windowControlsProps={{ justify: true, platform: type() === 'macos' ? 'macos' : 'windows' }}></WindowTitlebar>
                </WindowControlsContainer>
                <TitleContainer style={{ fontSize: '80px', color: '#5BBD6D' }}>
                    <CheckCircleFilled />
                </TitleContainer>
                <TitleContainer>扫描成功</TitleContainer>
                <TitleContainer>在小程序中点击允许登录即可</TitleContainer>
            </Container>
        );
    }

    return (
        <Container data-tauri-drag-region style={{
            justifyContent: 'center'
        }}>
            <WindowControlsContainer data-tauri-drag-region
                style={type() === 'macos' ? {
                    justifyContent: 'flex-start'
                } : {
                    justifyContent: 'flex-end'
                }}>
                <WindowTitlebar windowControlsProps={{ justify: true, platform: type() === 'macos' ? 'macos' : 'windows' }}></WindowTitlebar>
            </WindowControlsContainer>
            <TitleContainer>使用微信扫一扫登录</TitleContainer>
            <TitleContainer>「图灵忆」</TitleContainer>
            <QRCodeContainer>
                <img src={qrcode}></img>
            </QRCodeContainer>
        </Container>
    );
}


const Container = styled.div`
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    height: 100vh;
    width: 100vw;
    background-color: #FFF;
    justify-content: flex-start;
`;

const WindowControlsContainer = styled.div`
    width: 100vw;
    height: 30px;
    position: fixed;
    top:0;
    left:0;
    display: flex;
    align-items: center;
`;

const QRCodeContainer = styled.div`
    margin-top: 20px;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 220px;
    width: 220px;
`;


const TitleContainer = styled.div`
    line-height: 40px;
    font-size: 22px;
    font-weight: bold;
    color: #1A1A1A;
`;

